<template>
  <div class="c-bg-white" id="container">
    <div class="c-fs24 c-pz1000 c-br-tl10 c-br-tr10 c-p-l0 c-p-r0 c-m-auto0 c-p-b0 c-bg-white c-pf c-pv24 c-ph24" v-if="address">
      <div class="c-fc-xblack c-fs-26 c-lh36 c-mb20">{{address.modName}}</div>
      <div class="c-fc-sblack c-fs-24 c-lh34 c-mb16">{{address.address}}</div>
      <div id='callApp' class="c-fs24 c-fc-white c-br36 c-lh34 c-pv24 c-linebg-orange c-textAlign-c c-mt20">地图导航</div>
    </div>
  </div>
</template>
<script>
import { utilJs, wxUtilJs } from "@/utils/common.js";
export default {
  name: "DistanceAMap",
  data() {
    return {
      address: null
    };
  },
  beforeRouteLeave(to, from, next) {
    localStorage.removeItem('address');
    next();
  },
  methods: {
    //获取地图路径
    getDistance() {
      let that = this;
      //获取个人定位
      wxUtilJs.getLocation().then((res) => {
        let userXY = [res.longitude, res.latitude];
        let aMap = window.AMap;
          let map = new aMap.Map('container', {
            resizeEnable: true,
            zoom: 10
          });
          let position = new aMap.LngLat(that.address.lng * 1, that.address.lat * 1); //转换经纬度格式
          let button = document.getElementById('callApp');
          aMap.plugin('AMap.Driving', function () {
            let driving = new aMap.Driving({
              map: map,
              policy: aMap.DrivingPolicy.LEAST_TIME // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
            })
            let startLngLat = new aMap.LngLat(userXY[0], userXY[1]);
            let endLngLat = position;
            driving.search(startLngLat, endLngLat, function (status, result) {
              button.onclick = function () {
                driving.searchOnAMAP({
                  origin: result.origin,
                  destination: result.destination
                });
              }
            })
          })
      })
    },
  },
  mounted() {
    setDocumentTitle("地图导航");
    this.address = JSON.parse(localStorage.getItem('address'));
    utilJs.wechatConfig("", "", "", "", function () {}, true);
    if (window.AMap) {
      this.getDistance();
    } else {
      utilJs.syncLoadJs('https://webapi.amap.com/maps?v=1.4.15&callback=initAMap&key=da83ae2a89855d1b7cb0d07307160fc2');
      window.initAMap = () => {
        this.getDistance();
      }
    }

  },
  deactivated() {
  }
}
</script>